package com.atguigu.utils;

import com.atguigu.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author dl
 * @create 2020-04-21-22:41
 */
public class WebUtils {
	/**
	 * get map value to bean
	 * @param request HttpServletRequest
	 * @param t bean
	 * @param <T> Bean
	 * @return t bean
	 */
	public static<T> T map2Bean(HttpServletRequest request, T t) {
		try {
			// 将 request 中的参数转换成 map 然后转换成Bean对象
			BeanUtils.populate(t,request.getParameterMap());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * test myself
	 * @param request HttpServletRequest
	 * @param t bean
	 * @param <T> Bean
	 * @return t bean
	 */
	public static<T> T map2Bean2( T t) {/*HttpServletRequest request,*/
		Field[] fields = t.getClass().getDeclaredFields();
		for (Field field : fields) {
			// get field name
			String name = field.getName();
			Class<?> type = field.getType();
			System.out.println(type);
			// 将 name 的第一个字符转换成大写
//			String methodName = firstToUpperCase(name);
			/**
			 * private java.lang.Integer com.atguigu.domain.User.id
			 * id
			 * private java.lang.String com.atguigu.domain.User.username
			 * username
			 * private java.lang.String com.atguigu.domain.User.password
			 * password
			 * private java.lang.String com.atguigu.domain.User.email
			 * email
			 */
//			// get request value
//			String value = request.getParameter(name);
//			// set value
//			// 1 将 name 的第一个转换成大写
//			// 2 和 set 进行拼接得到方法
//			try {
//				t.getClass().getMethod("set" + name,field.getType());
//			} catch (NoSuchMethodException e) {
//				e.printStackTrace();
//			}
		}
		return t;
	}

	/**
	 * 获取登录的用户
	 * @param req
	 * @return
	 */
	public static User getLoginUser(HttpServletRequest req) {
		HttpSession session = req.getSession();
		return (User) session.getAttribute("user");
	}

//	public static String firstToUpperCase(String name) {
////		name.split('');
//		StringBuilder builder = new StringBuilder(name);
//		char c = builder.charAt(0);
//		builder.setCharAt();
//		return new String(split.toString());
//
//	}
}
